using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

# region Properties



# endregion


public partial class PoolToSPRelationship : System.Web.UI.Page
{
    public string entity;
    public string function;
    AdminServices.AdminServices proxy;
    AdminServices.ServiceProviderSearchRequest serviceProviderSearchRequest;
    AdminServices.PoolSearchRequest poolSearchRequest;
    AdminServices.HSDPrincipal currentPrincipal;
    private const string ENTITY_FIRST = "Pool";
    private const string ENTITY_SECOND = "Service Provider";


    protected void Page_Load(object sender, EventArgs e)
    {
        bool newEntity = false;
        if (Request["entity"] != null)
        {
            Session["entity"] = Request["entity"];
            //checks if entity has changed
            newEntity = true;
        }
        if (Request["function"] != null)
        {
            Session["function"] = Request["function"];
        }
        entity = Session["entity"].ToString();
        function = Session["function"].ToString();

        if (Session["currentPrincipal"] == null)
        {
            Session["currentPrincipal"] = GetPrincipal();
        }
        currentPrincipal = (AdminServices.HSDPrincipal)Session["currentPrincipal"];

        proxy = new AdminServices.AdminServices();


        if (!IsPostBack)
        {
            // only load reload controls if entity has changed
            if (newEntity)
            {
                setControls();
            }
            loadGrid();
        }
    }

    /// <summary>
    /// This function load the grid for the relevent entity
    /// </summary>
    private void loadGrid()
    {
        if (entity == ENTITY_FIRST)
        {
            getServiceProvidersByPool(int.Parse(tbPage.Text));
        }
        else
        {
            getPoolsByServiceProvider(int.Parse(tbPage.Text));
        }
    }
    /// <summary>
    /// This function set controls for the relevant entity
    /// </summary>
    private void setControls()
    {
        if (entity == ENTITY_FIRST)
        {
            lnkPool.Enabled = false;
            lnkServiceProvider.Enabled = true;
            ddlEntity.DataTextField = "PoolName";
            ddlEntity.DataValueField = "PoolID";
            ddlEntity.DataSource = getPools();
            assignEntityToGrid("DisplayName", ENTITY_SECOND, "ServiceProviderID");
            lblEntitySelect.Text = string.Format("Select {0}:", ENTITY_FIRST);
            gvResults.EmptyDataText = string.Format("No {0}s to {1}", ENTITY_SECOND, function);
        }
        else
        {
            lnkPool.Enabled = true;
            lnkServiceProvider.Enabled = false;
            ddlEntity.DataTextField = "DisplayName";
            ddlEntity.DataValueField = "ServiceProviderID";
            ddlEntity.DataSource = getServiceProviders();
            assignEntityToGrid("PoolName", ENTITY_FIRST, "PoolID");
            lblEntitySelect.Text = string.Format("Select {0}:", ENTITY_SECOND);
            gvResults.EmptyDataText = string.Format("No {0}s to {1}", ENTITY_FIRST, function);
        }
        ddlEntity.DataBind();             

        btnFunction.Text = function;

        if (function == "Search")
        {
            btnFunction.Visible = false;
            gvResults.Columns[0].Visible = false;
        }
    }

    private AdminServices.HSDPrincipal GetPrincipal()
    {
        proxy = new AdminServices.AdminServices();
        return proxy.ValidateUser("me", "!password01");
    }

    private void getServiceProvidersByPool(int pageIndex)
    {
        proxy = new AdminServices.AdminServices();

        serviceProviderSearchRequest = new AdminServices.ServiceProviderSearchRequest();
        serviceProviderSearchRequest.PoolID = ddlEntity.SelectedValue;

        //if we are adding we want service providers not in pool 
        //if deleting we want the service providers that are already in the pool
        if (function == "Add")
            serviceProviderSearchRequest.InPool = false;
        else
            serviceProviderSearchRequest.InPool = true;

        AdminServices.ServiceProvider[] results = proxy.ServiceProviderSearch(currentPrincipal, serviceProviderSearchRequest);        
  
        gvResults.DataSource = results;
        gvResults.PageIndex = pageIndex;
        gvResults.DataBind();
    }

    private void getPoolsByServiceProvider(int pageIndex)
    {
        proxy = new AdminServices.AdminServices();
        poolSearchRequest = new AdminServices.PoolSearchRequest();
        poolSearchRequest.ServiceProviderID = ddlEntity.SelectedValue;

        //if we are adding we want pool not with service providers 
        //if deleting we want the pools that are already with service providers
        if (function == "Add")
            poolSearchRequest.InServiceProvider = false;
        else
            poolSearchRequest.InServiceProvider = true;

        AdminServices.Pool[] results = proxy.PoolSearch(currentPrincipal, poolSearchRequest);        

        gvResults.DataSource = results;
        gvResults.PageIndex = pageIndex;
        gvResults.DataBind();
    }

    private void assignEntityToGrid(string dataField, string headerText, string dataKeyNames)
    {
        BoundField boundField = new BoundField();
        boundField.DataField = dataField;
        boundField.HeaderText = headerText;
        gvResults.Columns.Add(boundField);
        gvResults.DataKeyNames = new string[] { dataKeyNames };       
    }

    private AdminServices.Pool[] getPools()
    {
        proxy = new AdminServices.AdminServices();
        poolSearchRequest = new AdminServices.PoolSearchRequest();
        return proxy.PoolSearch(currentPrincipal, poolSearchRequest);
    }

    private AdminServices.ServiceProvider[] getServiceProviders()
    {
        proxy = new AdminServices.AdminServices();
        serviceProviderSearchRequest = new AdminServices.ServiceProviderSearchRequest();
        serviceProviderSearchRequest.InPool = true;
        return proxy.ServiceProviderSearch(currentPrincipal, serviceProviderSearchRequest);
    }
    protected void ddlEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadGrid();
    }

    private void performFunction()
    {
        List<AdminServices.ServiceProviderPoolLink> links = new List<AdminServices.ServiceProviderPoolLink>();
        //Loop through GridView Items
        foreach (GridViewRow gvr in gvResults.Rows)
        {
            //Retrieve records that are checked
            CheckBox checkBox = (CheckBox)gvr.FindControl("chkSelect");
            if (checkBox != null)
            {
                if (checkBox.Checked)
                {
                    AdminServices.ServiceProviderPoolLink link = new AdminServices.ServiceProviderPoolLink();
                    //Retrieve key value of each record based on GridViews DataKeyNames property 
                    //for the relevent entity
                    if (entity == ENTITY_FIRST)
                    {
                        link.ServiceProviderID = Convert.ToInt32(gvResults.DataKeys[gvr.RowIndex].Value);
                        link.PoolID = Convert.ToInt32(ddlEntity.SelectedValue);
                    }
                    else
                    {
                        link.PoolID = Convert.ToInt32(gvResults.DataKeys[gvr.RowIndex].Value);
                        link.ServiceProviderID = Convert.ToInt32(ddlEntity.SelectedValue);
                    }
                    links.Add(link);
                }
            }
        }

        //Change list to array of objects
        AdminServices.ServiceProviderPoolLink[] ServiceProviderPoolLinks = new AdminServices.ServiceProviderPoolLink[links.Count - 1];            
        ServiceProviderPoolLinks = (AdminServices.ServiceProviderPoolLink[])links.ToArray();

        if (function == "Add")
            proxy.ServiceProviderPoolLinksInsert(currentPrincipal, ServiceProviderPoolLinks);
        else
            proxy.ServiceProviderPoolLinksDelete(currentPrincipal, ServiceProviderPoolLinks);

        loadGrid();  
    }

    protected void btnFunction_Click(object sender, EventArgs e)
    {
        performFunction();
    }
    protected void gvResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (entity == "Pool")
            getServiceProvidersByPool(e.NewPageIndex);
        else
            getPoolsByServiceProvider(e.NewPageIndex);
        tbPage.Text = e.NewPageIndex.ToString();  
    }
}
